/*******************************************************************************
 * Copyright (c) 2009, 2013 EclipseSource and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    EclipseSource - initial API and implementation
 ******************************************************************************/
package it.rap.applications.movimenti.ricerche.core;

import static it.rap.applications.movimenti.ricerche.utils.ImageUtil.getImage;
import it.rap.application.logic.mappers.ContoCorrenteLogic;
import it.rap.application.logic.mappers.MovimentoLogic;
import it.rap.applications.container.IContainerPage;
import it.rap.applications.contributions.manager.utils.SubMenuAction;
import it.rap.applications.movimenti.ricerche.widget.LittleReportComposite;
import it.rap.applications.movimenti.ricerche.widget.MovimentoDataContainer;
import it.rap.applications.persistence.entities.contoCorrente.ContoCorrente;
import it.rap.applications.persistence.entities.movimento.Movimento;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableColorProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;


public class CorePage implements IContainerPage {

	public static final String ID_MOVIMENTO 		= "ID movimento";
	public static final String DATA_CONTABILE 		= "Data Contabile";
	public static final String DATA_VALUTA 			= "Data valuta";
	public static final String ADDEBITO 			= "Addebito";
	public static final String ACCREDITO			= "Accredito";
	public static final String DESCRIZIONE 			= "Descrizione";
	public static final String DESCRIZIONE_COMPLETA	= "Descrizione completa";
	public static Integer 	   DEFAULT_ACCOUNTS		= 1;
	
	public static final String[] PROPS = { ID_MOVIMENTO, DATA_CONTABILE, DATA_VALUTA, ACCREDITO, ADDEBITO, DESCRIZIONE, DESCRIZIONE_COMPLETA };

	private SashForm sashForm = null;
	//private TableViewer tv = null; 
	//private Table uiTableProperties;
	
	//private List<Movimento> propertiesList= new ArrayList<Movimento>();
	
	private String fileResultName;
	private String[] fileNames; 
	
//	private CellEditor[] editors = new CellEditor[7];
	private Composite parent = null;

	
	private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	private Text logText;
	
	//private DataNavigator dataNavigator;
	//private Composite compositeDataNavigator; 
	
	
	private List<SubMenuAction> actions = new ArrayList<SubMenuAction>();
	private List<SubMenuAction> ccActions = new ArrayList<SubMenuAction>();
	private Composite p_1;
	
	private ContoCorrente cc = new ContoCorrente();
	
	private LittleReportComposite littleReportComposite;
	private MovimentoDataContainer movimentoDataContainer;
 	/**
	 * @wbp.parser.entryPoint
	 */
	public void wBuilderEntriPoint(Composite parent){
		p_1 = new Composite( parent, SWT.NONE);
	    this.createControl( p_1 );
	}
	
	public void createControl(Composite _parent ) {
		cc.setState( DEFAULT_ACCOUNTS );
		ContoCorrenteLogic ccLogic = new ContoCorrenteLogic();
		ContoCorrente _firstCc = ccLogic.getContoCorrenteByFinder(cc);
		
		
		parent = _parent;
	  	Layout gl_p_1 = new GridLayout(1, false);
		parent.setLayout( gl_p_1 );
		
		Composite contoCorrenteSelected = new Composite(parent, SWT.NONE);
		contoCorrenteSelected.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
		RowLayout rl_contoCorrenteSelected = new RowLayout(SWT.HORIZONTAL);
		rl_contoCorrenteSelected.pack = false;
		rl_contoCorrenteSelected.wrap = false;
		contoCorrenteSelected.setLayout(rl_contoCorrenteSelected);
		
		Label lblFinecoBank = new Label(contoCorrenteSelected, SWT.NONE);
		lblFinecoBank.setText("Conto corrente selezionato: ");
		lblFinecoBank.setData( RWT.CUSTOM_VARIANT, "contoCorrenteSelectedLabel" ); 
		  

	    ToolBar ccToolBar = new ToolBar(contoCorrenteSelected,  SWT.NONE  );
	    ccToolBar.setData( RWT.CUSTOM_VARIANT, "contoCorrente" );
	    ToolItem ccDropDown = new ToolItem(ccToolBar, SWT.DROP_DOWN);
	    ccDropDown.setText( _firstCc.getBanca() );
	    ccDropDown.setImage( getImage( parent.getDisplay(), "fineco.png" ) );
	    ccDropDown.setToolTipText("Select for more accounts...");
	    ccDropDown.setData( RWT.CUSTOM_VARIANT, "contoCorrente" ); 
	    Menu ccMenu = new Menu( ccDropDown.getParent().getShell(), SWT.POP_UP );
	    ccMenu.setData( RWT.CUSTOM_VARIANT, "contoCorrente" );
	    ccDropDown.addListener( SWT.Selection, new DropDownSelectionListener( ccMenu ) );
	    CcSubMenuItemSelectionListener ccSubMenuListener = new CcSubMenuItemSelectionListener( ccDropDown );
		  
		initCCSubMenuAction();
		for( SubMenuAction action: ccActions  ){
		    MenuItem item = new MenuItem( ccMenu, SWT.PUSH );
		    item.setText( action.getName() );
		    item.setImage( action.getImage() );
		    item.setData( action );
		    item.addListener( SWT.Selection, ccSubMenuListener );
		}
		
		Composite headerComposite = new Composite(parent, SWT.NONE);
		headerComposite.setLayout(new RowLayout(SWT.HORIZONTAL));
		
	    ToolBar toolBar = new ToolBar(headerComposite,  SWT.NONE  );
	    ToolItem dropDown = new ToolItem(toolBar, SWT.DROP_DOWN);
	    dropDown.setText("Actions");
	    dropDown.setImage( getImage( parent.getDisplay(), "no-flag.png" ) );
	    dropDown.setToolTipText("Select for more actions...");
	    Menu menu = new Menu( dropDown.getParent().getShell(), SWT.POP_UP );
	    dropDown.addListener( SWT.Selection, new DropDownSelectionListener( menu ) );
	    SubMenuItemSelectionListener subMenuListener = new SubMenuItemSelectionListener( dropDown );
		  
		initSubMenuAction();
		for( SubMenuAction action: actions  ){
		    MenuItem item = new MenuItem( menu, SWT.PUSH );
		    item.setText( action.getName() );
		    item.setImage( action.getImage() );
		    item.setData( action );
		    item.addListener( SWT.Selection, subMenuListener );
		}
		
		littleReportComposite = new LittleReportComposite(headerComposite, cc);
	
	    sashForm = new SashForm(parent, SWT.VERTICAL);
	    sashForm.setLayoutData(new GridData(GridData.FILL, SWT.FILL, true, true ));
	    
	    movimentoDataContainer = new MovimentoDataContainer( sashForm, cc );
	    movimentoDataContainer.setTotaleMovimenti( littleReportComposite.getTotMov() );
	    
	    /*
	    Composite dataComposite = new Composite(sashForm, SWT.NONE);
		GridLayout gl_dataComposite = new GridLayout(1, false);
		gl_dataComposite.verticalSpacing = 0;
		gl_dataComposite.marginWidth = 0;
		gl_dataComposite.marginHeight = 0;
		gl_dataComposite.horizontalSpacing = 0;
		dataComposite.setLayout(gl_dataComposite);
	    

		compositeDataNavigator = new Composite(dataComposite, SWT.NONE);
		RowLayout rl_compositeDataNavigator = new RowLayout(SWT.HORIZONTAL);
		rl_compositeDataNavigator.center = true;
		compositeDataNavigator.setLayout( rl_compositeDataNavigator);
		compositeDataNavigator.setVisible(true);
		//compositeDataNavigator.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false, 2, 1));
		
		Button previousRangeDataButton = new Button(compositeDataNavigator, SWT.NONE);
		previousRangeDataButton.addSelectionListener(new SelectionAdapter() {
			
			private static final long serialVersionUID = 6024936608021483098L;

			@Override
			public void widgetSelected(SelectionEvent e) {
				if( currentDataOffset >= currentDataLimit ){
					currentDataOffset = currentDataOffset - currentDataLimit;
					currentDataOffsetText.setText( ""+currentDataOffset );
					currentDataLimitText.setText( ""+currentDataLimit );
					currentDataOffsetText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
					currentDataLimitText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
					loadData();
					dataNavigator.refresh(new BigDecimal(currentDataOffset), new BigDecimal( currentDataLimit ), littleReportComposite.getTotMov() );
				}
			}
		});
		previousRangeDataButton.setText("<");
		
		currentDataOffsetText = new Text(compositeDataNavigator, SWT.BORDER );
		currentDataOffsetText.setLayoutData(new RowData(27, SWT.DEFAULT));
		currentDataOffsetText.addModifyListener(new ModifyListener() {
			
			private static final long serialVersionUID = -8546729160323808058L;

			public void modifyText(ModifyEvent event) {
				currentDataOffset = Integer.parseInt( currentDataOffsetText.getText() );
				currentDataOffsetText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);				
			}
		});
		currentDataOffsetText.setText( ""+currentDataOffset );
		
		Label _l = new Label( compositeDataNavigator, SWT.NONE);
		_l.setText(" - ");
		
		currentDataLimitText = new Text(compositeDataNavigator, SWT.BORDER );
		currentDataLimitText.setLayoutData(new RowData(27, SWT.DEFAULT));
		currentDataLimitText.addModifyListener(new ModifyListener() {
			
			private static final long serialVersionUID = 211724654169235244L;

			public void modifyText(ModifyEvent event) {
				currentDataLimit = Integer.parseInt( currentDataLimitText.getText() );				
				currentDataLimitText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
			}
		});
		currentDataLimitText.setText( ""+currentDataLimit );
				
		Button nextRangeDataButton = new Button(compositeDataNavigator, SWT.NONE);
		nextRangeDataButton.addSelectionListener(new SelectionAdapter() {
			
			private static final long serialVersionUID = 3742953187019857365L;

			@Override
			public void widgetSelected(SelectionEvent e) {
				if (littleReportComposite.getTotMov().compareTo( new BigDecimal( currentDataOffset + currentDataLimit )) >= 0 ){
					currentDataOffset = currentDataOffset + currentDataLimit;
					currentDataOffsetText.setText( ""+currentDataOffset );
					currentDataLimitText.setText( ""+currentDataLimit );
					currentDataOffsetText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
					currentDataLimitText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
					loadData();
					dataNavigator.refresh(new BigDecimal(currentDataOffset), new BigDecimal( currentDataLimit ), littleReportComposite.getTotMov() );
				} else {
					//estraggo i rimanenti
				}
			}
		});
		nextRangeDataButton.setText(">");
		
		dataNavigator = new DataNavigator();
		dataNavigator.createControl( compositeDataNavigator , new BigDecimal( currentDataOffset ), new BigDecimal( currentDataLimit ), littleReportComposite.getTotMov() );
		dataNavigator.setVisible(false);
	    
	    Composite composite = new Composite(dataComposite, SWT.NONE);
	    composite.setLayout(new GridLayout(1, false));
	    composite.setLayoutData(new GridData(GridData.FILL, SWT.FILL, true, true ));
	    
	    tv = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION );
	    tv.setData( RWT.CUSTOM_VARIANT, "tvContainer" );
	    uiTableProperties = tv.getTable();
	    uiTableProperties.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
	    
	    tv.setContentProvider(new MovimentoContentProvider());
	    tv.setLabelProvider(new MovimentoLabelProvider());
	    tv.setInput( propertiesList );
	    
	    TableColumn tableColumn_1 = new TableColumn(uiTableProperties, SWT.CENTER);
	    tableColumn_1.setWidth( 10 * ID_MOVIMENTO.length() );
	    tableColumn_1.setText( ID_MOVIMENTO );
	    TableColumn tableColumn_2 = new TableColumn(uiTableProperties, SWT.CENTER);
	    tableColumn_2.setWidth( 11 * DATA_CONTABILE.length() );
	    tableColumn_2.setText( DATA_CONTABILE );				
	    TableColumn tableColumn_3 = new TableColumn(uiTableProperties, SWT.CENTER);
	    tableColumn_3.setWidth( 11 * DATA_VALUTA.length() );
	    tableColumn_3.setText( DATA_VALUTA );
	    TableColumn tableColumn_4 = new TableColumn(uiTableProperties, SWT.CENTER);
	    tableColumn_4.setWidth( 11 * ACCREDITO.length() );
	    tableColumn_4.setText( ACCREDITO );
	    TableColumn tableColumn_5 = new TableColumn(uiTableProperties, SWT.CENTER);
	    tableColumn_5.setWidth( 11 * ADDEBITO.length() );
	    tableColumn_5.setText( ADDEBITO );
	    
	    TableColumn tableColumn_6 = new TableColumn(uiTableProperties, SWT.CENTER);
	    tableColumn_6.setWidth( 25 * DESCRIZIONE.length() );
	    tableColumn_6.setText( DESCRIZIONE );
	    
	    TableColumn tableColumn_7 = new TableColumn(uiTableProperties, SWT.CENTER);
	    tableColumn_7.setWidth( 50 * DESCRIZIONE_COMPLETA.length() );
	    tableColumn_7.setText( DESCRIZIONE_COMPLETA );
	    
	    uiTableProperties.setLinesVisible(true);
	    uiTableProperties.setHeaderVisible(true);
	    
		tv.setColumnProperties(PROPS);
		tv.setCellModifier(new MovimentoCellModifier(tv));
		editors[1] = new TextCellEditor(uiTableProperties);
		editors[2] = new TextCellEditor(uiTableProperties);
		editors[3] = new TextCellEditor(uiTableProperties);
		editors[4] = new TextCellEditor(uiTableProperties);
		editors[5] = new TextCellEditor(uiTableProperties);
		editors[6] = new TextCellEditor(uiTableProperties);
		tv.setCellEditors(editors);
				
	    for (int i = 0, n = uiTableProperties.getColumnCount(); i < n; i++) {
	      uiTableProperties.getColumn(i).pack();
	    } 
		editors[0] = null;
		*/
	    
		logText = new Text(sashForm, SWT.BORDER | SWT.MULTI);
		logText.setVisible( false );
		sashForm.setWeights(new int[] {1, 1});
	}

	private void initCCSubMenuAction() {
		ContoCorrenteLogic cLogic = new ContoCorrenteLogic();
		List<ContoCorrente> cList = (List<ContoCorrente>) cLogic.selectAll(0, 100);

		for(final ContoCorrente c: cList){
			String img = "no-flag.pg";
			if ( c.getBanca().equalsIgnoreCase( "fineco bank" ) ){
				img = "fineco.png";
			} else {
				img = "poste.png";
			}
			ccActions.add(
					new SubMenuAction( c.getBanca(), getImage( parent.getDisplay(), img ), c ){
							@Override
							public void handleAction() {
								chengeContoCorrenteSelected( c );
							}
					    }
					);
		}
		
	}
/*
	public TableViewer getTv() {
		return tv;
	}
	
	public void setTv(TableViewer tv) {
		this.tv = tv;
	}
	
	public Table getUiTableProperties() {
		return uiTableProperties;
	}
	
	public void setUiTableProperties(Table uiTableProperties) {
		this.uiTableProperties = uiTableProperties;
	}
	
	public List<Movimento> getPropertiesList() {
		return propertiesList;
	}
	
	public void setPropertiesList(List<Movimento> propertiesList) {
		this.propertiesList = propertiesList;
	}
	*/
	public String getFileResultName() {
		return fileResultName;
	}
	
	public void setFileResultName(String fileResultName) {
		this.fileResultName = fileResultName;
	}
	
	public String[] getFileNames() {
		return fileNames;
	}
	
	public void setFileNames(String[] fileNames) {
		this.fileNames = fileNames;
	}
	private Shell getShell() {
		return Display.getCurrent().getActiveShell();
	}
	
	private void initSubMenuAction(){
		actions.add(
		new SubMenuAction("Save", getImage( parent.getDisplay(), "no-flag.png" ) ){
				@Override
				public void handleAction() {
					save();
				}
		    }
		);
		actions.add(
			new SubMenuAction("Load from file",  getImage( parent.getDisplay(), "loadFromFile.png" ) ){
				@Override
				public void handleAction() {
					loadFromFile();
				}
		    }		
		);
		actions.add(
			   new SubMenuAction("Load from DB", getImage( parent.getDisplay(), "refreshDB.png" ) ){
					@Override
					public void handleAction() {
						//loadData();
						movimentoDataContainer.loadData();
						movimentoDataContainer.setVisible(true);
						//dataNavigator.setVisible(true);
						//compositeDataNavigator.setVisible(true);
					}
			    }
		);
		actions.add(
			 new SubMenuAction("Crea un movimento", getImage( parent.getDisplay(), "add_obj.png" ) ){
					@Override
					public void handleAction() {
						creaMovimento();
					}
			    }
		);
	}
	
	private void creaMovimento(){
		Movimento p = new Movimento();
	    p.setIdMovimento( new Float("0") );
	    p.setDataContabile( new Date() );
	    p.setDataValuta( new Date() );
	    p.setAccredito( new Float("0") );
	    p.setAddebito( new Float("0") );
	    p.setDescrizione( "Mov. descr." );
	    p.setDescrizioneCompleta("Mov. descr. completa.");
	    p.setContoCorrente( cc );
	    movimentoDataContainer.addMovimento(p);
	}
	
	private void chengeContoCorrenteSelected(ContoCorrente cc){
		this.cc = cc;
		littleReportComposite.refreshReport( cc );
		movimentoDataContainer.setCc(cc);
		movimentoDataContainer.setTotaleMovimenti( littleReportComposite.getTotMov() );
		movimentoDataContainer.getDataNavigator().setTotaleMovimenti( littleReportComposite.getTotMov() );
		movimentoDataContainer.getDataNavigator().setCurrentDataOffset(new BigDecimal("0"));
		movimentoDataContainer.getPropertiesList().clear();
		movimentoDataContainer.setCurrentDataOffset(new Integer("0"));
		movimentoDataContainer.refresh();
		System.out.println("cc change!! Selected is: " + DEFAULT_ACCOUNTS);
	}
	
	private void save(){
		try {
			//new Logger().info( "Save click..." );	
			//BusinessLogicMovimenti businessLogic = new BusinessLogicMovimenti( BusinessLogic.MYBATIS_SQLITE_ACCESS  );					
			MovimentoLogic mLogic = new MovimentoLogic();
//			for(Movimento m: propertiesList){
			for(Movimento m: movimentoDataContainer.getPropertiesList()){	
//				if ( businessLogic.esisteMovimento( m ) == 0 ){
//					businessLogic.insert( m );
//				}
				if ( mLogic.esisteMovimento( m ) == 0 ){
					mLogic.persist( m );
				}
			}	
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}	
	}
	
	public class SubMenuItemSelectionListener implements Listener {

		private static final long serialVersionUID = -3928858460335365662L;
		private final ToolItem dropDown;

	    public SubMenuItemSelectionListener( ToolItem dropDown ) {
	      this.dropDown = dropDown;
	    }

	    public void handleEvent( Event event ) {
	      MenuItem item = ( MenuItem )event.widget;
	      SubMenuAction action = ( SubMenuAction )item.getData();
	      
	      if ( action.getImage() != null ){
	    	  dropDown.setImage( item.getImage() );
	    	  dropDown.setToolTipText( "Your last action was: " + action.getName() );
	      }
	      dropDown.setData( action );
	      
	      executeAction( action );
	    }

		private void executeAction(SubMenuAction action) {
			action.handleAction();
		}
	}
	
	public class CcSubMenuItemSelectionListener implements Listener {

		private static final long serialVersionUID = -3928858460335365662L;
		private final ToolItem dropDown;

	    public CcSubMenuItemSelectionListener( ToolItem dropDown ) {
	      this.dropDown = dropDown;
	    }

	    public void handleEvent( Event event ) {
	      MenuItem item = ( MenuItem )event.widget;
	      SubMenuAction action = ( SubMenuAction )item.getData();
	      
	      if ( action.getImage() != null ){
	    	  dropDown.setImage( item.getImage() );
	    	  dropDown.setText( item.getText() );
	    	  dropDown.setToolTipText( "Your last action was: " + action.getName() );
	      }
	      dropDown.setData( action );
	      
	      executeAction( action );
	    }

		private void executeAction(SubMenuAction action) {
			action.handleAction();
		}
	}


	public class DropDownSelectionListener implements Listener {

		private static final long serialVersionUID = 3413309950050125164L;
		private final Menu menu;

	    public DropDownSelectionListener( Menu menu ) {
	      this.menu = menu;
	    }

	    public void handleEvent( Event event ) {
	      ToolItem dropDown = ( ToolItem )event.widget;
	      if( event.detail == SWT.ARROW ) {
	        Point point = dropDown.getParent().toDisplay( event.x, event.y );
	        menu.setLocation( point );
	        menu.setVisible( true );
	      } else {
	    	  final SubMenuAction dropDownAction = (SubMenuAction) dropDown.getData();
	    	  if ( dropDownAction == null ) return;
	    	  MessageDialog confirm = new MessageDialog(parent.getShell(), "Recall action?", null, "Recall action "+dropDownAction.getName()+"?", MessageDialog.CONFIRM, new String[]{ "OK", "Annulla" }, 1){
				private static final long serialVersionUID = 4972001426579301330L;
				@Override
	    	      protected int getShellStyle() {
	    	        return super.getShellStyle() | SWT.SHEET;
	    	      }
	    	      @Override
	    	      public boolean close() {
	    	        boolean result = super.close();
	    	        int code = getReturnCode();
	    	        if ( code == 0 ){
	    	        	dropDownAction.handleAction();
	    	        }
	    	        return result;
	    	      }
	    	    };
	    	    confirm.open();
	    	  }
	      }
	    }
	/*
	private void loadData(){
		try {
			if ( logText != null && logText.isVisible() && !logText.isDisposed() ){
				logText.setText("");
				logText.setVisible( false );
				if ( sashForm != null )sashForm.setWeights(new int[] {1, 1});
			}
			
			//BusinessLogicMovimenti businessLogic = new BusinessLogicMovimenti( BusinessLogic.MYBATIS_SQLITE_ACCESS  );
			MovimentoLogic mLogic = new MovimentoLogic();
			List<Movimento> mList = mLogic.selectAll(cc, currentDataOffset, currentDataLimit);
			propertiesList.clear();	  
			propertiesList.addAll( mList );
			Collections.sort(propertiesList, new MovimentoComparable());
			Collections.reverse( propertiesList );
			tv.refresh();	
			
		} catch( Exception e){
			e.printStackTrace();
		}
	}
	*/
	
	private void loadFromFile(){

		  //propertiesList.clear();
		  movimentoDataContainer.getPropertiesList().clear();
		 
		  //FileUpload fileUpload = new FileUpload( parent, SWT.MULTI );			 
			
		  FileDialog fileDialog = new FileDialog( getShell(), SWT.TITLE | SWT.SINGLE );
		  fileDialog.setText( "Upload file movimenti" );			 
		  fileDialog.open();
		  fileNames = fileDialog.getFileNames();
		  BigDecimal mInserted = new BigDecimal("0");
		  BigDecimal analizedRecords = new BigDecimal("0");
		  StringBuffer parsedRecords = new StringBuffer("");
		  if (  fileNames != null && fileNames.length > 0 && !fileNames[0].equalsIgnoreCase("") ){
			  File f1 = new File( fileNames[0] );
	  		  if(	f1.canRead() ){
	  			  try {
	  				  //BusinessLogicMovimenti businessLogic = new BusinessLogicMovimenti( BusinessLogic.MYBATIS_SQLITE_ACCESS  );
	  				  MovimentoLogic mLogic = new MovimentoLogic();
	  				  InputStream is = new FileInputStream( f1 );
	  				  BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
		    		  String line = "";
		    		  br.readLine(); //Salto L'intestazione
					  while ((line  = br.readLine()) != null) {
						  analizedRecords = analizedRecords.add( new BigDecimal("1") );
						  try {
							  // Deal with the line							 
							  Movimento m = new Movimento();
							  m.setContoCorrente( movimentoDataContainer.getCc() );
							  m.setDataContabile( sdf.parse(  line.split(";")[0]  ) );
							  m.setDataValuta( sdf.parse(  line.split(";")[1]  ) );
							  
							  m.setAccredito( line.split(";")[2].compareTo("")==0?null:Float.parseFloat( line.split(";")[2]  ));
							  m.setAddebito( line.split(";")[3].compareTo("")==0?null:Float.parseFloat( line.split(";")[3]  ));
							  
							  m.setDescrizione( line.split(";")[4] );
							  m.setDescrizioneCompleta( line.split(";")[5] );
							  
							  if ( mLogic.esisteMovimento( m ) == 0 ){
								  mLogic.persist( m );									  
								  mInserted = mInserted.add( new BigDecimal("1") );
								  parsedRecords.append("|  NEW-ROW#|:").append( analizedRecords ).append( " " ).append( line ).append("\n");										  
							  } else {
								  parsedRecords.append("|FOUND-ROW#|:").append( analizedRecords ).append( " " ).append( line ).append("\n");				
							  }
							  //propertiesList.add( m );
							  movimentoDataContainer.getPropertiesList().add( m );

						  } catch ( Exception ex ){
							  ex.printStackTrace();
							  parsedRecords.append("|WRONG-ROW#|:").append( analizedRecords ).append( " " ).append( line ).append("\n");								  
						  }							 
					  	}	
					    //tv.refresh();
					    movimentoDataContainer.refresh();
					    if ( !logText.isVisible() ){
					    	logText.setVisible( true );
					    }
					  	logText.setText( parsedRecords.toString() );
		    		    // Done with the file    		    	
						br.close();
						br = null;
		    		    is = null;
						
		    		    MessageDialog.openInformation( getShell(), "File Upload complete! ", analizedRecords + " analized records. " + mInserted + " new movements!");
					} catch (IOException e1) {
						e1.printStackTrace();
					} catch (Exception e1) {
						e1.printStackTrace();
					}  		    	
	  		    }	
		  }
		
	}
}
class MovimentoComparable implements Comparator<Movimento>{
	public int compare(Movimento arg0, Movimento arg1) {
		return arg0.getDataContabile().compareTo( arg1.getDataContabile() );
	}
} 

class DataNavigator  {
	Label navigatorLabel;
	Composite parent;

	/**
	 * @wbp.parser.entryPoint
	 */
	public void wBuilderEntriPoint(Composite parent){ 
	     this.createControl( parent, new BigDecimal(0), new BigDecimal(20), new BigDecimal(300) );
	}
	void createControl(Composite parent, BigDecimal currentDataOffset, BigDecimal currentDataLimit, BigDecimal totMov){	
		this.parent = parent;
		navigatorLabel = new Label( parent, SWT.NONE | SWT.FILL);		
		refresh(currentDataOffset, currentDataOffset.add( currentDataLimit ) , totMov);
		
	}
	
	void refresh(BigDecimal currentDataOffset, BigDecimal currentDataLimit, BigDecimal totMov){
		if( navigatorLabel != null ){
			try {
				navigatorLabel.setText( new StringBuffer("records: ").append( currentDataOffset ).append( " To " ).append( currentDataOffset.add( currentDataOffset.add( currentDataLimit ).compareTo( totMov )<=0?currentDataLimit:totMov.subtract( currentDataOffset  ) ) ).append(" of ").append( ""+totMov ).toString() );
			} catch (Exception e ){
				
			}
			navigatorLabel.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
		}
		this.parent.getParent().redraw();
	}
	
	void setVisible(boolean visible){
		navigatorLabel.setVisible(visible);
	}

}

class MovimentoContentProvider implements IStructuredContentProvider {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Object[] getElements(Object inputElement) {
		return ((List<?>) inputElement).toArray();
	}

	public void dispose() {
	}

	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
	}
}

class MovimentoLabelProvider implements ITableLabelProvider,  ITableColorProvider  {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	
	public Image getColumnImage(Object element, int columnIndex) {
		return null;
	}

	public String getColumnText(Object element, int columnIndex) {
		Movimento p = (Movimento) element;
		switch (columnIndex) {
		case 0:
			return p.getIdMovimento()==null?"":Float.toString(p.getIdMovimento());
		case 1:
			return p.getDataContabile()==null?"":sdf.format(p.getDataContabile());
		case 2:
			return p.getDataValuta()==null?"":sdf.format(p.getDataValuta());
		case 3:
			return p.getAccredito()==null?"":Float.toString( p.getAccredito() );			
		case 4:
			return  p.getAddebito()==null?"":Float.toString(p.getAddebito());
		case 5:
			return p.getDescrizione()==null?"":p.getDescrizione();
		case 6:
			return p.getDescrizioneCompleta()==null?"":p.getDescrizioneCompleta();
			
		}
		return null;
	}

	public void addListener(ILabelProviderListener listener) {
	}

	public void dispose() {
	}

	public boolean isLabelProperty(Object element, String property) {
		return false;
	}

	public void removeListener(ILabelProviderListener listener) {
	}

	public Color getForeground(Object element, int columnIndex) {
		switch (columnIndex) {
		case 3:
			return new Color(Display.getCurrent(), 0, 255, 0 );		
		case 4:
			return new Color(Display.getCurrent(), 255, 0, 0 );		
		}
		return null;
	}

	public Color getBackground(Object element, int columnIndex) {
		return null;
	}
}


class MovimentoCellModifier implements ICellModifier {
	  private Viewer viewer;
	  private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	  
	  public MovimentoCellModifier(Viewer viewer) {
	    this.viewer = viewer;
	  }

	  public boolean canModify(Object element, String property) {
	    return true;
	  }

	  public Object getValue(Object element, String property) {
	    Movimento p = (Movimento) element;
	    if (CorePage.ID_MOVIMENTO.equals(property))
	      return p.getIdMovimento()==null?"":p.getIdMovimento().toString();
	    else if (CorePage.DATA_CONTABILE.equals(property))
	      return p.getDataContabile()==null?"":sdf.format( p.getDataContabile() );
	    else if (CorePage.DATA_VALUTA.equals(property))
	      return p.getDataValuta()==null?"":sdf.format( p.getDataValuta() );
	    else if (CorePage.ACCREDITO.equals(property))
		      return p.getAccredito()==null?"":p.getAccredito().toString();
	    else if (CorePage.ADDEBITO.equals(property))
		      return p.getAddebito()==null?"":p.getAddebito().toString();
	    else if (CorePage.DESCRIZIONE.equals(property))
		      return p.getDescrizione()==null?"":p.getDescrizione();
	    else if (CorePage.DESCRIZIONE_COMPLETA.equals(property))
		      return p.getDescrizioneCompleta()==null?"":p.getDescrizioneCompleta();
	    else
	      return null;
	  }

	  public void modify(Object element, String property, Object value) {
	    if (element instanceof Item) element = ((Item) element).getData();

	    Movimento p = (Movimento) element;
	    if (CorePage.ID_MOVIMENTO.equals(property))
	      p.setIdMovimento( value==null?null:Float.parseFloat( (String)value ) );	   
	    else if (CorePage.DATA_CONTABILE.equals(property)){	
	    	try {
				p.setDataContabile( sdf.parse( (String) value ) );
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	    
	    else if (CorePage.DATA_VALUTA.equals(property)){
			try {
				p.setDataValuta( sdf.parse( (String) value ) );
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
		else if (CorePage.ACCREDITO.equals(property))
		      p.setAccredito( value==null||value.equals("")?null:Float.parseFloat( (String)value ));
	    else if (CorePage.ADDEBITO.equals(property))
		      p.setAddebito( value==null||value.equals("")?null:Float.parseFloat( (String)value ));
	    else if (CorePage.DESCRIZIONE.equals(property))
		      p.setDescrizione( value==null||value.equals("")?null:(String) value);
	    else if (CorePage.DESCRIZIONE_COMPLETA.equals(property))
		      p.setDescrizioneCompleta( value==null||value.equals("")?null:(String) value);
	    viewer.refresh();
	  }
	}